package com.atguigu.utils;

import java.util.*;
import java.util.concurrent.*;

public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(10);
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5)+1);
                    System.out.println(Thread.currentThread().getName()+"占到车位了");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5)+1);
                    System.out.println(Thread.currentThread().getName()+"离开车位了");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }
    }
}
